package ru.btabank.dom.xpath.expression;

import java.util.ArrayList;

import ru.btabank.dom.xpath.XPathException;

public class NumberFunction extends FunctionCall {

    public NumberFunction() {
        super();
    }

    public Object evaluate(NodeSet context) throws XPathException {
        ArrayList values = super.evaluateValues(context);
        Object value;

        if (values.size() != 1)
            throw new XPathException("number() function requires one argument.");
        else
            value = values.get(0);

        if (value instanceof Double)
            return value;
        else if (value instanceof String)
            try {
                return new Double((String)value);
            } catch (NumberFormatException exception) {
                return new Double(Double.NaN);
            }
        else if (value instanceof Boolean) {
            if (((Boolean)value).booleanValue() == true)
                return new Double(1);
            else
                return new Double(0);
        } else if (value instanceof NodeSet) {
            NodeSet nodeSet = (NodeSet)value;
            if (nodeSet.getLength() == 0)
                return new Double(Double.NaN);

            throw new UnsupportedOperationException("Not supported yet...");
        }
        return new Double(Double.NaN);
    }
}
